-- Copyright (c) 2024 Huawei Technologies Co., Ltd.
-- openUBMC is licensed under Mulan PSL v2.
-- You can use this software according to the terms and conditions of the Mulan PSL v2.
-- You may obtain a copy of Mulan PSL v2 at:
--         http://license.coscl.org.cn/MulanPSL2
-- THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
-- EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
-- MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
-- See the Mulan PSL v2 for more details.

local log = require 'mc.logging'
local collection_helper = {}

function collection_helper.for_each(collection, cb, input_processor, output_parser, ...)
    local ok, msg, data, ret
    local result = {}
    for _, item in pairs(collection) do
        data = item
        if input_processor then
            data = input_processor(item)
        end
        ret = cb(data, ...)
        ok, msg = pcall(cb, data, ...)
        if ok then
            ret = msg
        else
            log:error(msg)
        end
        if output_parser then
            ret = output_parser(ret)
        end
        if ret then
            table.insert(result, ret)
        end
    end
    return result
end

return collection_helper
